package pemks.dao;

import pemks.util.DBUtil;

import java.sql.*;

public class FileSecretDAO {
    // 保存文件密钥
    public boolean saveKF(int fileId, String kf, String owner) {
        String sql = "INSERT INTO file_secrets (file_id, kf, owner) VALUES (?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, fileId);
            pstmt.setString(2, kf);
            pstmt.setString(3, owner);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            return false;
        }
    }

    // 获取文件密钥
    public String getKF(int fileId) {
        String sql = "SELECT kf FROM file_secrets WHERE file_id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, fileId);
            ResultSet rs = pstmt.executeQuery();
            return rs.next() ? rs.getString("kf") : null;
        } catch (SQLException e) {
            return null;
        }
    }

    // 删除文件密钥
    public boolean deleteKF(int fileId) {
        String sql = "DELETE FROM file_secrets WHERE file_id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, fileId);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            return false;
        }
    }
}